var $modal = $("#modal");
var $image = $("#image");
var $loadding = $(".loadding");
var currentImageInput = null;
var cropper = null;
var height = document.body.offsetHeight;
var width = document.body.offsetWidth;
var token = "H82tzsO0bwxy2ywpnSb41zyWam1Tw_-rlfEsBzc-:sseD-Cpx1yE5fCm9F8U23zt8Ma8=:eyJzY29wZSI6IjZtZ2NuIiwiZGVhZGxpbmUiOjE1MTU1NjcxMzF9";


var getUpToken = function(){
	$.getJSON("c",function(r){
		token = r.uptoken;
		console.log(token);
	})
}


var closeModal = function() {
	$modal.hide();
}

var loadImg = function(e) {
	currentImageInput = e.target;
	console.log('currentImageInput',currentImageInput)
	console.log('currentImageInput.files',currentImageInput.files)
	if(currentImageInput.files.length > 0) {
		imgHandler(currentImageInput.files[0]);
	}
}

var initCropper = function() {
	cropper = new Cropper($image[0], {
		aspectRatio: 'NaN',
		viewMode: 0,
		rotatable: true,
		guides: true,
		dragMode: "move",
		background: true,
		movable: true,
		cropBoxMovable: false,
		cropBoxResizable: false,
		minContainerHeight: height - 40,
		minContainerWidth: width,
		ready: function() {
			console.log("ready")
			//获取裁剪框尺寸
			var data = $(currentImageInput).data();

			cropper.setCropBoxData({
				left : (width - data.width) / 2,
				top : width <780?((height - data.height) / 4) :((height - data.height) / 2),
				"width": data.width,
				"height": data.height
			})
		}
	});
}

var imgHandler = function(file) {
	
	if(!file) {
		alert('请选择图片');
		return;
	}
	if(cropper == null){
		alert('图片裁剪器正在准备中，请稍后再试');
		return;
	}

	var fileName = file.name;
	var fileSize = file.size;
	console.log('fileName',fileName)
	console.log('fileSize',fileSize)
	var fileType = fileName.substring(fileName.lastIndexOf('.'), fileName.length).toLowerCase();
	if(fileType !== '.jpg' && fileType !== '.jpeg' && fileType !== '.gif' && fileType !== '.png' && fileType !== '.bmp') {
		alert("请选择jpg,png,gif,bmp格式的图片");
		return;
	}

	//new一个FileReader实例
	var reader = new FileReader();
	console.log('reader',reader)
	reader.readAsDataURL(file);
	console.log('reader',reader)
	console.log('file',file)
	reader.onload = function(e) {
//		console.log('e',e)
		
		$image.attr('src', e.target.result);
		cropper.replace(e.target.result);
		$(currentImageInput).val("");
//		console.log('$(currentImageInput)',$(currentImageInput))
		$modal.show();
//		console.log('$modal',$modal)
	};
}

var big = function() {
	cropper.zoom(0.1);
}
var small = function() {
	cropper.zoom(-0.1);
}
var rotate = function() {
	cropper.rotate(5);
}

var upload = function() {
	 $loadding.show();
	
//	var cropBoxData = $image.cropper('getCropBoxData');
//	var croppedCanvas = $image.cropper('getCroppedCanvas', cropBoxData);
	
//	var src = croppedCanvas.toDataURL('img/cropped.jpg');
	
	var src = cropper.getCropBoxData();
	src = cropper.getCroppedCanvas(src).toDataURL('img/cropped.jpg');
	console.log(src)
//	var src = cropper.getCroppedCanvas({
//		 
//	}).toDataURL();
//	console.log('src',src)
	
	toQiNiu(src);	
}

var toQiNiu = function(picBase) {

	if(token == null){
		alert("请重新获取token");
		return ;
	}
	
	//去掉.data:image/png;base64
	picBase = picBase.substring(22);
//	console.log('picBase',picBase)
	// 文件流大小计算
	function fileSize(str) {
		console.log('str',str)
		var fileSize;
		if(str.indexOf('=') > 0) {
			var indexOf = str.indexOf('=');
			str = str.substring(0, indexOf); //把末尾的'='号去掉
		}

		fileSize = parseInt(str.length - (str.length / 8) * 2);
		console.log('fileSize',fileSize)
		return fileSize;
	}

	//strToJson
	function strToJson(str) {
		var json = eval('(' + str + ')');
		return json;
	}

	var url = "http://upload.qiniu.com/putb64/" + fileSize(picBase);
//	console.log('url',url)
	var xhr = new XMLHttpRequest();
	xhr.onreadystatechange = function() {
		if(xhr.readyState == 4) {
			var keyText = xhr.responseText;
			keyText = strToJson(keyText);
			console.log(keyText)
			var data = $(currentImageInput).data();
			console.log('$(currentImageInput)',$(currentImageInput))
			console.log('$(currentImageInput).data()',$(currentImageInput).data());
			$loadding.hide();
			//七牛压缩参数
			//?imageMogr2/auto-orient/thumbnail/800x800%3E
			
			picUrl = "http://ox2f59gjo.bkt.clouddn.com/" + keyText.key+"?imageMogr2/auto-orient/thumbnail/"+data.width+"x"+data.height+"%3E";
			$modal.hide();
			 //关闭截图框，将图片放入原来的位置,隐藏+号
			 $(currentImageInput).parent().find(".upload").hide();
			 $(currentImageInput).parent().find(".result").attr('src',picUrl).show();
			 $(currentImageInput).parent().find(".url").html(keyText.key).show();
			 console.log('success!')
		}
	};

	xhr.open("POST", url, true);
	xhr.setRequestHeader("Content-Type", "application/octet-stream");
	xhr.setRequestHeader("Authorization", "UpToken " + token);
	xhr.send(picBase);

}
 initCropper();
 //getUpToken();
